import java.util.concurrent.ThreadPoolExecutor;

/**
 * @program: data_structures_algorithms
 * @description: 链表排序-归并排序思想
 * @author: lld
 * @create: 2021-04-10 21:19
 **/
public class ListMergeSort {
    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        ListNode listNode4 = new ListNode(4);
        ListNode listNode5 = new ListNode(5);
        listNode4.next=listNode2;
        listNode2.next=listNode1;
        listNode1.next=listNode3;
        listNode3.next=listNode5;

        ListNode listNode = mergeSort(listNode4, null);
        System.out.println(listNode);
    }
    /**
     * @Description: 拆分再合并
     **/
    private static ListNode mergeSort(ListNode head, ListNode end) {
        if (head == null) {
            return null;
        }
//        注意只有头尾，要把头的next置空
        if (head.next == end) {
            head.next = null;
            return head;
        }
//        快慢指针找到链表中点
        ListNode fast = head, slow = head;
        while (fast != end && fast.next != end) {
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode mid = slow;
        ListNode left = mergeSort(head, mid);
        ListNode right = mergeSort(mid, end);

        return merge(left, right);
    }

    /**
     * @Description: 合并两个有序链表
     **/
    private static ListNode merge(ListNode l1, ListNode l2) {
        if (l1 == null && l2 == null) {
            return null;
        }
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
//        伪结点
        ListNode dummy = new ListNode(0);
        ListNode cur = dummy;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                cur.next = l1;
                l1 = l1.next;
            } else {
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }
//        合并多出来的
        if (l2 != null) {
            cur.next = l2;
        }
        if (l1 != null) {
            cur.next = l1;
        }
        return dummy.next;
    }

    private static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            return "{" + val +
                    "," + next +
                    '}';
        }
//        ThreadPoolExecutor
    }
}
